package com.group3.merchant.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group3.entity.DishType;
import com.group3.entity.Merchant;
import com.group3.merchant.service.IDishTypeService;
import com.group3.merchant.service.IMerchantService;
import com.group3.merchant.service.impl.DishTypeServiceImpl;
import com.group3.merchant.service.impl.MerchantServiceImpl;
import com.group3.merchant.validator.IValidator;
import com.group3.merchant.validator.impl.LoginPasswordValidator;
import com.group3.merchant.validator.impl.LoginUsernameValidator;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IMerchantService mservice = new MerchantServiceImpl();
	private IDishTypeService dservice = new DishTypeServiceImpl();
	private IValidator uv = new LoginUsernameValidator();
	private IValidator pv = new LoginPasswordValidator();
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		login(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		login(request, response);
	}

	private void login(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		PrintWriter writer = response.getWriter();
		List<String> errMsg = new ArrayList<>();
		String mName = request.getParameter("mName");
		String password = request.getParameter("password");
		List<String> l1 = pv.validate(password);
		List<String> l2 = uv.validate(mName);
		errMsg.addAll(l1);
		errMsg.addAll(l2);
		if (errMsg.size() != 0) {
			request.setAttribute("errMsg", errMsg);
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
			}
		HttpSession session = request.getSession();
		ServletContext context = request.getServletContext();

//		System.out.println("username:" + mName + ",password:" + password);

		boolean isLogin = false;
		String type = null;
		String status = null;

		// service
		Merchant merchant = mservice.login(mName, password);
		List<DishType> tlists = dservice.showAllType();
		if (merchant != null) {
			List<String> list = mservice.getStatus(merchant);
			if(list == null) {
				errMsg.add("Admin Service shutdown!!!");
				request.setAttribute("errMsg", errMsg);
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			}
			System.out.println("List: " + list);

			type = list.get(0).toLowerCase();
			status = list.get(1);
			
			System.out.println("Login: " + type + "..." + status);

			if (status == null) {
				status = "white";
			} else {
				status = status.toLowerCase();
			}
			isLogin = true;
		}
		if (isLogin) {
			session.setAttribute("tlists", tlists);
			session.setAttribute("loginToken", merchant);
			session.setAttribute("dType", "000");
			session.setAttribute("MType", type);
			session.setAttribute("mstatus", status);
			Map<String, String> amap = (Map<String, String>) context.getAttribute(merchant.getmId());
			
			if (amap == null) {
				amap = new HashMap<String, String>();
			}
			amap.put("mstatus", status);
			System.out.println("Login mid: " + merchant.getmId());
			System.out.println("Login amap: " + amap);
			context.setAttribute(merchant.getmId(), amap);

			// request.getServletContext().setAttribute("MStatus", status);
			// request.getSession().setAttribute("MStatus", status);
			/*
			 * assessing()----->reject.jsp reject(reason)------->reject.jsp
			 * assessed&&white------>listDis assessed&&black------>pending
			 */

			if ("assessed".equals(type)) {
				if ("white".equals(status)) {
					response.sendRedirect("mainpage.html");
				} else if ("black".equals(status)) {
					response.sendRedirect("pending.jsp");
				}
				return;
			}
			if ("assessing".equals(type) || "reject".equals(type)) {
				response.sendRedirect("reject.jsp");
			}
			return;

		} else {
			writer.write("<h1>NO such merchant user, please return to login again or register.</h1>");
			writer.write("<a href=\"http://localhost:8080/Msys/login.jsp\">click here</a>");
//			response.sendRedirect("login.jsp");
			return;
		}
	}

}
